﻿using MD5Hash;
using MediatR;
using Yuekao.API.Read.Command;
using Yuekao.Domain.API;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.dto;
using Yuekao.Domain.Entitys;

namespace Yuekao.API.Read.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<List<UserDTO>>>
    {
        private readonly IBaseRepository<UserModel> userbaseRepository;
        private readonly IBaseRepository<RoleModel> rolebaseRepository;

        public LoginCommandHandler(IBaseRepository<RoleModel> rolebaseRepository, IBaseRepository<UserModel> userbaseRepository)
        {
            this.rolebaseRepository = rolebaseRepository;
            this.userbaseRepository = userbaseRepository;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<UserDTO>>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<UserDTO>> result = new APIResult<List<UserDTO>>();

            var list1 = rolebaseRepository.GetAll();
            var list = userbaseRepository.GetAll();
            var res = from a in list
                      join b in list1
                      on a.RoleId equals b.RoleId
                      select new UserDTO
                      {
                          Id = a.Id,
                          UserName = a.UserName,
                          UserLickname = a.UserLickname,
                          RoleId = a.RoleId,
                          RoleName = b.RoleName,
                          UserPass = a.UserPass
                      };
            var query = res.Where(x => x.UserName == request.UserName).ToList();
            if (query.Count() == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "用户名不存在";
                return Task.FromResult(result);
            }
            var pwd = request.UserPass.GetMD5();
            query = query.Where(x => x.UserPass == pwd).ToList();
            if (query.Count() == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "密码不匹配";
                return Task.FromResult(result);
            }
            result.Code = APIEnum.Success;
            result.Message = "登录成功";
            result.Data = query.ToList();
            result.Token = "";
            return Task.FromResult(result);
        }
    }
}
